/*!
 * @Author: luoob
 * @Date: 2021-03-29 21:59:00
 * @Last Modified by: luoob
 * @Last Modified time: 2021-03-29 21:59:00
 * @Instruduction: http 请求器
 */

import { HOST, HOST_PREFIX } from 'src/config/env'
import { isValidURL } from 'src/common/utils/validate'
import { User } from 'src/common/storage'
import { successHandler, errorHandler } from './handlers'
import axios from 'axios'

// 只做增删改查
export type Methods =
    'get' |
    'GET' |
    'post' |
    'POST' |
    'put' |
    'PUT' |
    'delete' |
    'DELETE'

export interface XhrParams {
    url: string
    method: Methods
    params: any
}

export interface IResponse {
    status: number
    message: string
    data: any
}

// 创建两个 axios 实例的原因
// 一个用于短地址
// 一个用于完整的 url 地址
const ins = axios.create({
    baseURL: HOST + HOST_PREFIX,
    timeout: 1000 * 20
})
const ainstance = axios.create({
    timeout: 1000 * 10
})

const xhr = ({ url, params, method = 'get' }: XhrParams): Promise<IResponse> => {
    let instance = ins
    // 如果是完整的 url 路径
    if (isValidURL(url)) instance = ainstance

    // 当 header 没有 token 时
    if (!instance.defaults.headers.common['Authorization']) {
        instance.defaults.headers.common['Authorization'] = User.getToken() || ''
    }


    const useBody = ['post', 'put'].includes(method.toLocaleLowerCase())
    return instance({
        url,
        method,
        params: useBody ? undefined : params,
        data: useBody ? params : undefined
    })
        .then(successHandler)
        .catch(errorHandler)
}

export default xhr

